<template>
  <div class="player">
    <audio
      :src="getSongsUrl"
      autoplay
      ref="audio"
      :loop="modeIndex === 2 ? true : false"
      @pause="musicPause()"
      @play="playLoad()"
      @emptied="refersh()"
      @timeupdate="audioTimeUpdate()"
      @ended="musicEnded()"
      @volumechange="audioVolumeChange()"
    ></audio>
    <div class="player-left">
      <player-cover
        :song="getCurrentCover"
        class="player-cover"
        @getCurrentMusic="showPure"
      ></player-cover>
    </div>
    <div class="player-center">
      <div class="player-center-toggle">
        <div
          class="player-mode player-center-toggle-item"
          @click.prevent="toggleMode"
        >
          <a href="#" title="顺序播放" v-if="modeIndex === 0">
            <i class="iconfont iconliebiaoshunxu"></i>
          </a>
          <a href="#" title="随机播放" v-if="modeIndex === 1">
            <i class="iconfont iconicon--"></i>
          </a>
          <a href="#" title="单曲循环" v-if="modeIndex === 2">
            <i class="iconfont iconxunhuan"></i>
          </a>
        </div>
        <div class="player-pre player-center-toggle-item">
          <i class="iconfont iconshangyishou" @click="preMusic"></i>
        </div>
        <div
          class="player-player-type player-center-toggle-item"
          @click="toggle()"
        >
          <i class="iconfont iconbofang1" v-if="isPlay"></i>
          <i class="iconfont iconzanting" v-if="!isPlay"></i>
        </div>
        <div class="player-next player-center-toggle-item">
          <i class="iconfont iconxiayishou" @click="nextMusic"></i>
        </div>
      </div>
      <div class="player-center-progress">
        <div class="player-center-progress-time">{{ getCurrentTime }}</div>
        <div class="player-center-progress-progress">
          <el-slider
            :max="duration"
            :value="currentTime"
            :show-tooltip="false"
            @change="handleAudioDrag"
            @input="handleAudioDraging"
          ></el-slider>
        </div>
      </div>
    </div>
    <div class="player-right">
      <div class="player-right-tool">
        <div class="player-right-tool-volumn">
          <el-slider
            :max="100"
            class="player-volum-slider"
            :value="currentVolume"
            @input="handleVolumnDraging"
            @change="handleVolumnClick"
          ></el-slider>
        </div>
        <div class="player-right-tool-lyric">
          <a href="#" title="歌单" @click="isShowPlayList = !isShowPlayList">
            <i class="iconfont iconsonglist"></i>
          </a>
        </div>
      </div>
    </div>
    <transition name="player-pure-side">
      <player-pure
        v-if="isPure"
        :song="playList[currentIndex]"
        :lyric="getLyric"
        :currentTime="currentTime"
      ></player-pure>
    </transition>
    <player-list :musicList="playList" @changeCurrentMusic="changeCurrentMusic" v-if="isShowPlayList" :currentPlayingIndex="currentIndex" :playState="isPlay"></player-list>
  </div>
</template>
<script>
import playerCover from "./player-cover";
import playerPure from "./player-pure";
import playerList from "./Player-list"
import moment from "moment";

import { _getLyric } from "network/detail";
import { mapState } from 'vuex';
export default {
  name: "",
  components: {
    playerCover,
    playerPure,
    playerList,
  },
  data() {
    return {
      playList: [],
      /**播放列表
      @params {
      this.index=index;
      this.name=song.name;
      this.artist=song.artist;
      this.src=url;
      this.pic=song.pic;
      this.id=id;
      this.song=song
      }
      */
      currentIndex: null, //当前播放歌曲
      currentTime: null, //当前播放时间
      currentVolume: 50, //当前播放音量
      modeIndex: 0, //音乐播放模式
      isPlay: true, //是否在播放歌曲
      duration: null, //歌曲时长
      isMusicDrag: false, //是否在拖拽进度条
      isMusicClick: false,
      musicDragingTime: null, //拖动进度条到的时间点
      isPure: false,
      lyric: "",
      sliderBuffered: true, // 创建进度条缓存标志
      isShowPlayList: false, //是否展示播放列表
    };
  },
  computed: {
    ...mapState(['_playList']),
    getSongsUrl() {
      return [
        this.playList[this.currentIndex] &&
          this.playList[this.currentIndex].src,
      ];
    },
    getCurrentCover() {
      return this.playList[this.currentIndex];
    },
    playerClass() {
      return [];
    },
    getCurrentTime() {
      return moment(new Date(this.currentTime * 1000)).format("mm:ss");
    },
    getLyric() {
      if (this.playList.length != 0 && this.playList[this.currentIndex].id) {
        _getLyric(this.playList[this.currentIndex].id).then((res) => {
          if (res.status == 200) {
            this.lyric = res.data.lrc.lyric || "暂无歌词";
          }
        });
      }
      return this.lyric;
    },
  },
  mounted() {
    /* 设置歌单到localStorage */
    if (localStorage.getItem("playList")) {
      this.playList = JSON.parse(localStorage.getItem("playList"));
      this.currentIndex = Number(localStorage.getItem("leaveSongIndex"));
    }
    /* 设置音量 */
    if (localStorage.getItem("musicVolume")) {
      this.currentVolume = Number(localStorage.getItem("musicVolume"));
    }
    /* 给歌曲进度条设置事件 */
    /**
     *  给ui组件修改样式，添加事件
     * */
    let musicProgressElm = document.getElementsByClassName(
      "el-slider__button-wrapper"
    );
    musicProgressElm[0].setAttribute(
      "style",
      "width: 16px; height:16px; top: -10px"
    );
    let bollButtonElm = musicProgressElm[0].childNodes[0];
    bollButtonElm.addEventListener("mousedown", () => {
      // 这里是要设置当点击时， this.currentTime 不被audio设置
      this.isMusicDrag = true;
      this.isMusicClick = false;
    });
    bollButtonElm.addEventListener("mouseup", () => {
      // 这里是要设置当点击时， this.currentTime 不被audio设置
      this.isMusicDrag = false;
    });
    let sliderElm = document.getElementsByClassName("el-slider__runway");
    sliderElm[0].addEventListener("mousedown", () => {
      this.isMusicDrag = true;
      this.isMusicClick = true;
    });

    /* 监听playMusic事件 */
    this.$bus.$on("playMusic", (playList, index, musicList) => {
      if (playList.length == 0) {
        return;
      }
      /* 歌单存到storeage里面 或者cookie */
      this.playList = [];
      let playListFilter = [];
      /* 过滤掉没有音乐地址的歌曲 */
      playListFilter = playList.filter((item) => {
        return item.src;
      });
      /* 要对playList根据playList.index重新排序 */
      playListFilter = playListFilter.sort((a, b) => {
        return a.index - b.index;
      });
      this.playList = playListFilter;
      localStorage.setItem("playList", JSON.stringify(this.playList));
      this.setCurrentIndex(index);
    });
  },
  methods: {
    moment,
    /* 设置即将要播放的歌曲 */
    setCurrentIndex(index) {
      // 目前只完成主页面点击最新音乐
      this.currentIndex = index;
    },
    /* 切换播放模式 */
    toggleMode() {
      if (this.modeIndex === 2) {
        this.modeIndex = 0;
      } else {
        this.modeIndex++;
      }
    },
    /* 切换播放状态：暂停 播放 */
    toggle() {
      if (this.isPlay && this.$refs.audio.readyState === 4) {
        this.$refs.audio.play();
      } else {
        this.$refs.audio.pause();
      }
    },
    /* 监听音乐加载 */
    playLoad() {
      console.log("ready");
      this.isPlay = false;
      /* 获取歌曲时长 */
      this.duration = this.$refs.audio.duration;
    },
    /* 监听音乐暂停 */
    musicPause() {
      this.isPlay = true;
      localStorage.setItem("leaveSongIndex", this.currentIndex);
    },
    preMusic() {
      if (this.currentIndex === 0) {
        this.currentIndex = this.playList.length - 1;
      } else {
        this.currentIndex--;
      }
    },
    nextMusic() {
      this.musicEnded();
      switch (this.modeIndex) {
        case 0:
        case 2:
          this.currentIndex === this.playList.length - 1
            ? (this.currentIndex = 0)
            : this.currentIndex++;
          break;
        case 1:
          let tempIndex = this.currentIndex;
          while (tempIndex === this.currentIndex) {
            tempIndex = Math.floor(Math.random() * this.playList.length);
          }
          this.currentIndex = tempIndex;
          break;
      }
    },
    /* 记录当前以及退出时正在播放歌曲的index */
    refersh() {
      localStorage.setItem("leaveSongIndex", this.currentIndex);
    },
    /**返回当前的播放时间 */
    audioTimeUpdate() {
      /* 获取dom节点，只需要获取一次 */
      // if(this.sliderBuffered) {
      //   this.sliderBuffered = false
      //   let sliderElm = document.getElementsByClassName('el-slider__runway')
      //   let slider_bar_buffered = document.getElementsByClassName('el-slider__bar')[0].cloneNode(true)
      //   slider_bar_buffered.setAttribute('class','el-slider_bar_buffered')
      //   slider_bar_buffered.setAttribute('style','width: 20%;background-color: #000;height: 100%')
      //   sliderElm[0].appendChild(slider_bar_buffered)
      //   // slider_bar_buffered
      //   console.log(slider_bar_buffered);
      // }
      /* 进度条缓存 */
      // if(this.$refs.audio.buffered != 'undefined' && this.$refs.audio.buffered.length > 0) {
      //   const timeRanges = this.$refs.audio.buffered
      //   console.log(timeRanges.end(timeRanges.length - 1));
      //   console.log(this.currentTime);
      // }
      if (!this.isMusicDrag && !this.isMusicClick) {
        this.currentTime = this.$refs.audio.currentTime;
      }
    },
    /* 当前音乐播放结束 */
    musicEnded() {
      /* 判断当前音乐播放模式：顺序:0、随机:1、单曲循环:2 */
      switch (this.modeIndex) {
        case 0:
          this.currentIndex === this.playList.length - 1
            ? (this.currentIndex = 0)
            : this.currentIndex++;
          break;
        case 1:
          let tempIndex = this.currentIndex;
          while (tempIndex === this.currentIndex) {
            tempIndex = Math.floor(Math.random() * this.playList.length);
          }
          this.currentIndex = tempIndex;
          break;
        case 2:
          this.currentIndex = this.currentIndex;
          break;
      }
    },
    /* 拖拽音乐播放进度条 */
    handleAudioDrag(time) {
      if (!this.$refs.audio) {
        return;
      }
      if (this.isMusicClick) {
        this.$refs.audio.currentTime = this.musicDragingTime;
      }
      if (!this.isMusicDrag) {
        this.$refs.audio.currentTime = this.musicDragingTime;
      }
      this.isMusicDrag = false;
      this.isMusicClick = false;
    },
    handleAudioDraging(time) {
      if (this.isMusicDrag) {
        this.musicDragingTime = time;
      }
    },

    /***  音量控制 ****/
    /* 监控歌曲音量改变 */
    audioVolumeChange(volum) {
      // console.log(volum);
    },
    handleVolumnDraging(value) {
      let volume = value / 100;
      this.currentVolume = value;
      this.$refs.audio.volume = volume;
      localStorage.setItem("musicVolume", this.currentVolume);
    },
    handleVolumnClick(value) {
      let volume = value / 100;
      this.$refs.audio.volume = volume;
      localStorage.setItem("musicVolume", this.currentVolume);
    },

    /* 控制pure展开，关闭 */
    showPure(song) {
      this.isPure = !this.isPure;
    },
    /** 点击歌单列表 切换正在播放的歌曲 */
    changeCurrentMusic(index, id) {
      this.setCurrentIndex(index)
    }
  },
};
</script>
<style lang="less" scoped>
.player {
  height: 100%;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: absolute;
  z-index: 100;
  &-left {
    width: 400px;
    height: 100%;
    background: rgb(255, 255, 255); // 根据主题色设置
  }
  &-cover {
    padding: 5px;
  }
  &-center {
    width: 1400px;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 5px;
    background: rgb(255, 255, 255); // 根据主题色设置
    &-toggle {
      width: 20%;
      height: 50%;
      display: flex;
      justify-content: space-around;
      align-items: center;
      margin-top: 5px;
    }
    &-progress {
      width: 50%;
      height: 50%;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      &-time {
        width: 10%;
        height: 40px;
        text-align: center;
        line-height: 40px;
      }
      &-progress {
        margin: 0;
        height: 100%;
        width: 85%;
      }
    }
  }
  &-right {
    width: 300px;
    height: 100%;
    display: flex;
    align-items: center;
    background: rgb(255, 255, 255); // 根据主题色设置
    &-tool {
      display: flex;
      align-items: center;
      width: 100%;
      &-volumn {
        width: 60%;
      }
      &-lyric {
        margin-left: 30px;
      }
    }
  }
}
.el-slider {
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}
// .el-slider__runway .el-slider__button-wrapper {
//   width: 16px !important;
//   height: 16px !important;
//   top: -10px !important;
// }
.player-player-type {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: rgb(244, 244, 244);
  display: flex;
  justify-content: center;
  align-items: center;
}
a {
  text-decoration: none;
  color: rgb(0, 0, 0);
}
.iconfont {
  cursor: pointer;
}
.iconbofang1 {
  margin-left: 3px;
}
.player-pure-side-enter-active {
  animation: slideInUp var(--animation-base-time);
}
.player-pure-side-leave-active {
  animation: slideInUp var(--animation-base-time) reverse;
}
</style>